<template>
  <div class="recruitment-page">
    <!-- 顶部导航栏 -->
    <HeaderNav :active-menu="activeMenu" @menu-select="handleMenuSelect" @user-command="handleUserCommand" />

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧边栏 -->
      <Sidebar :active-sidebar="activeSidebar" @sidebar-select="handleSidebarSelect" />

      <!-- 右侧内容区域 -->
      <main class="recruitment-main">
        <div class="content-wrapper">
          <!-- 页面标题 -->
          <div class="page-header">
            <h1>招聘广场</h1>
            <p>发现合适的工作机会，开启职业新篇章</p>
          </div>

          <!-- 搜索和筛选区域 -->
          <div class="filter-panel">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input v-model="searchKeyword" placeholder="搜索职位或公司名称" prefix-icon="el-icon-search"
                  @keyup.enter="fetchJobs"></el-input>
              </el-col>
              <!-- 公司筛选下拉框 -->
              <el-col :span="7">
                <el-select v-model="selectedCompany" placeholder="选择公司" @change="fetchJobs">
                  <el-option label="全部公司" value=""></el-option>
                  <el-option label="阿里巴巴" value="阿里巴巴"></el-option>
                  <el-option label="腾讯" value="腾讯"></el-option>
                  <el-option label="百度" value="百度"></el-option>
                  <el-option label="字节跳动" value="字节跳动"></el-option>
                  <el-option label="华为" value="华为"></el-option>
                </el-select>
              </el-col>
              <!-- 城市筛选下拉框 -->
              <el-col :span="7">
                <el-select v-model="selectedLocation" placeholder="工作城市" @change="fetchJobs">
                  <el-option label="全部城市" value=""></el-option>
                  <el-option label="北京" value="北京"></el-option>
                  <el-option label="上海" value="上海"></el-option>
                  <el-option label="广州" value="广州"></el-option>
                  <el-option label="深圳" value="深圳"></el-option>
                </el-select>
              </el-col>
              <el-col :span="2">
                <el-button type="primary" @click="fetchJobs">搜索</el-button>
              </el-col>
            </el-row>
          </div>

          <!-- 职位列表 -->
          <div class="jobs-list">
            <!-- 无数据时显示 -->
            <div v-if="jobs.length === 0 && pagination.total === 0" class="no-data">
              <el-empty description="暂无职位数据"></el-empty>
            </div>

            <!-- 职位卡片（匹配后端字段） -->
            <el-card v-for="job in jobs" :key="job.job_id" class="job-card" hover>
              <div class="job-header">
                <div class="company-info">
                  <div class="company-details">
                    <h3>{{ job.title }}</h3>
                    <p>{{ job.company }}</p>
                  </div>
                </div>
                <div class="salary">{{ job.salary_range }}</div>
              </div>

              <div class="job-body">
                <div class="job-tags">
                  <el-tag>{{ job.location }}</el-tag>
                </div>

                <div class="job-desc">
                  {{ job.description.substring(0, 100) }}...
                </div>
              </div>

              <div class="job-footer">
                <div class="post-time">
                  发布于 {{ formatTime(job.created_at) }} · 有效期至 {{ formatDate(job.expires_at) }}
                </div>
                <div class="actions">
                  <el-button size="small" type="primary" @click="viewJobDetail(job.job_id)">
                    查看详情
                  </el-button>
                  <el-button size="small" type="success" @click="applyJob(job.job_id)" v-if="userStore.isLoggedIn()">
                    立即申请
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 分页 -->
          <div class="pagination" v-if="pagination.total > 0">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="pagination.currentPage" :page-sizes="[10, 20, 30]" :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"></el-pagination>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElEmpty } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '@/stores/user'

// 导入组件
import HeaderNav from '@/components/layout/HeaderNav.vue'
import Sidebar from '@/components/layout/Sidebar.vue'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const activeMenu = ref('recruitment')
const activeSidebar = ref('recruitment')

// 搜索和筛选参数（只保留公司和城市）
const searchKeyword = ref('')
const selectedCompany = ref('')  // 公司筛选参数
const selectedLocation = ref('')     // 城市筛选参数

// 职位数据（匹配后端返回结构）
const jobs = ref([])
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})



// 格式化时间（多久前）
const formatTime = (timeString) => {
  const date = new Date(timeString)
  const now = new Date()
  const diffInSeconds = Math.floor((now - date) / 1000)

  if (diffInSeconds < 60) return `${diffInSeconds}秒前`
  if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}分钟前`
  if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}小时前`
  return `${Math.floor(diffInSeconds / 86400)}天前`
}

// 格式化日期（年月日）
const formatDate = (timeString) => {
  const date = new Date(timeString)
  return date.toLocaleDateString()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  fetchJobs()
}
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  fetchJobs()
}

// 查看职位详情
const viewJobDetail = (jobId) => {
  router.push(`/jobs/${jobId}`)
}

// 申请职位
const applyJob = async (jobId) => {
  try {
    // 获取当前用户简历
    const resumesResponse = await axios.get('/api/resumes/my', {
      headers: { token: localStorage.getItem('token') }
    })

    if (resumesResponse.data.code === 0 && resumesResponse.data.data.list.length === 0) {
      ElMessage.warning('请先创建简历再申请职位')
      return router.push('/resumes')
    }

    // 投递第一个简历（实际场景可让用户选择）
    const resumeId = resumesResponse.data.data.list[0].resume_id
    const response = await axios.post(`/api/jobs/${jobId}/apply`,
      { resume_id: resumeId },
      { headers: { token: localStorage.getItem('token') } }
    )

    if (response.data.code === 0) {
      ElMessage.success('申请成功，等待雇主回复')
    } else {
      ElMessage.error(response.data.msg || '申请失败')
    }
  } catch (error) {
    ElMessage.error('操作失败，请稍后重试')
    console.error(error)
  }
}

const fetchJobs = async () => {
  try {
    const params = {
      keyword: searchKeyword.value,
      company: selectedCompany.value,  // 传递公司筛选参数
      location: selectedLocation.value,        // 传递城市筛选参数
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    };

    const response = await axios.get('/api/jobs', { params });
    console.log('后端返回完整数据：', response.data);

    const resData = response.data;
    if (resData.code === 0 && resData.data) {
      jobs.value = resData.data.list || [];
      pagination.value = resData.data.pagination || {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        totalPages: 0
      };
    } else {
      ElMessage.error(resData.msg || '获取职位列表失败');
      jobs.value = [];
      pagination.value.total = 0;
    }
  } catch (error) {
    ElMessage.error('获取职位失败，请稍后重试');
    console.error(error);
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchJobs()
})

// 导航相关方法（保持不变）
const handleMenuSelect = (index) => {
  activeMenu.value = index
  router.push({ name: index.charAt(0).toUpperCase() + index.slice(1) })
}
// 新增：侧边栏导航处理
const handleSidebarSelect = (index) => {
  activeSidebar.value = index
  switch (index) {
    case 'dashboard':
      router.push('/')
      break
    case 'social':
      router.push('/social')
      break
    case 'circles':
      router.push('/circle')
      break
    case 'chat':
      router.push('/chat')
      break
    case 'lost-found':
      router.push('/lost-and-found')
      break
    case 'second-hand':
      router.push('/second-hand')
      break
    case 'network':
      router.push('/network')
      break
    default:
      ElMessage.success(`当前已是在 ${index}页面`)
  }
}
const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile': router.push('/profile'); break
    case 'resume':  // 新增：处理"我的简历"命令
      router.push('/resumes')  // 跳转到简历页面路由
      break
    case 'logout':
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      ElMessage.success('已退出登录')
      router.push('/login')
      break
    default: ElMessage.info(`执行命令: ${command}`)
  }
}
</script>

<style scoped>
.recruitment-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* 主内容区域 */
.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.recruitment-main {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  margin-left: 280px;
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.page-header p {
  color: #666;
}

.filter-panel {
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.jobs-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin: 20px 0;
}

.no-data {
  text-align: center;
  padding: 40px 0;
}

.job-card {
  transition: all 0.3s;
}

.job-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.company-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.company-logo {
  width: 60px;
  height: 60px;
}

.company-details h3 {
  font-size: 18px;
  margin-bottom: 4px;
}

.company-details p {
  color: #666;
  font-size: 14px;
}

.salary {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.job-body {
  margin-bottom: 16px;
}

.job-tags {
  margin-bottom: 12px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.job-desc {
  color: #333;
  line-height: 1.6;
}

.job-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.post-time {
  color: #999;
}

.actions {
  display: flex;
  gap: 8px;
}

.pagination {
  margin-top: 32px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .recruitment-main {
    margin-left: 240px;
    padding: 16px;
  }

  .filter-panel .el-row {
    flex-direction: column;
    gap: 12px;
  }

  .filter-panel .el-col {
    width: 100%;
  }
}
</style>